import sqlite3
from typing import List, Dict, Any
from utils.db_manager import db_manager
from utils.logger import logger

class OrderRepository:
    @staticmethod
    def get_pending_open_orders() -> List[Dict[str, Any]]:
        """查询pending_orders表，status==未成交，所有为开多"""
        sql = """
            SELECT order_id, open_price
            FROM pending_orders
            WHERE status='未成交'
        """
        try:
            rows = db_manager.execute_query(sql, max_retries=5, retry_delay=0.3)
            logger.info(f"成功获取 {len(rows)} 条未成交订单")
            return [
                {'order_id': row[0], 'open_price': float(row[1]), 'mode': '开多'}
                for row in rows
            ]
        except sqlite3.OperationalError as e:
            logger.error(f"获取未成交订单失败: {e}")
            # 返回空列表而不是抛出异常，避免影响上层业务
            return []
        except Exception as e:
            logger.error(f"获取未成交订单意外错误: {e}")
            return []

    @staticmethod
    def get_pending_close_orders() -> List[Dict[str, Any]]:
        """查询orders表，status==待完结，所有为平多"""
        sql = """
            SELECT order_id, close_price
            FROM orders
            WHERE status='待完结'
        """
        try:
            rows = db_manager.execute_query(sql, max_retries=5, retry_delay=0.3)
            logger.info(f"成功获取 {len(rows)} 条待完结订单")
            return [
                {'order_id': row[0], 'close_price': float(row[1]), 'mode': '平多'}
                for row in rows
            ]
        except sqlite3.OperationalError as e:
            logger.error(f"获取待完结订单失败: {e}")
            # 返回空列表而不是抛出异常，避免影响上层业务
            return []
        except Exception as e:
            logger.error(f"获取待完结订单意外错误: {e}")
            return []

    @staticmethod
    def assemble_order_cache() -> Dict[str, List[Dict[str, Any]]]:
        """组装订单缓存"""
        try:
            result = {
                'open': OrderRepository.get_pending_open_orders(),
                'close': OrderRepository.get_pending_close_orders()
            }
           # logger.info(f"订单缓存组装完成，开多订单: {len(result['open'])}，平多订单: {len(result['close'])}")
            return result
        except Exception as e:
            logger.error(f"组装订单缓存失败: {e}")
            return {'open': [], 'close': []} 